<?php
if(!defined('inside')) die('You do not have permission to execute this file directly.');

/**
* Controller class file.
*
* @author Federico Ramirez <fedekiller@gmail.com>
* @link http://code.google.com/p/akaikiwi/
* @copyright Copyright &copy; 2008-2011 Federico Ramirez
* @license http://www.opensource.org/licenses/mit-license.php MIT Licence
*/
class Controller {
	/**
	 * This method will load a view
	 * @param String $name the name of the view
	 */
	protected function view($view, $data = array(), $includes_available = FALSE) {
		if($data == NULL) $data = array();
		
		if($includes_available) {
			preg_match_all("/<\?php(.*)\?>/i", $this->get_view($view), $codes, PREG_SET_ORDER);
			$html = preg_split("/<\?php(.*)\?>/i", $this->get_view($view));
			for($i = 0; $i < count($html); $i++) {				
				preg_match_all("/<view\s+name=\"(.*)\"\s*\/>/i", $html[$i], $views, PREG_SET_ORDER);
				$html_final = preg_split("/<view\s+name=\"(.*)\"\s*\/>/i", $html[$i]);
				for($j = 0; $j < count($html_final); $j++) {
					echo $html_final[$j];
					if($j < count($views)) {
						$this->view($views[$j][1], $includes_available, $data);
					}
				}

				if($i <= count($codes) - 1) {
					eval($codes[$i][1]);
				}
				
			}
		} else {
			eval('?>' . $this->get_view($view));
		}
	}

	protected function get_view($view) {
		if(!file_exists('app/views/' . $view . '.php')) {
			throw new AkaikiwiException('Cannot load the specified view: ' . $view);
		}
		return file_get_contents('app/views/' . $view . '.php');
	}

	protected function show_view($tpl, $data = array()) {
		eval('?>' . $tpl);
	}
}
